﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.Linq;
using System.Linq;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web;
using MLY.Dal;
using MLY.Bll;
using System.Drawing;
using System.Threading;
using System.Globalization;
using System.Web.UI.HtmlControls;

namespace MLY.LTR
{
    public partial class BulkUpdate2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //TitleLiteral.Text = Dictionary.Translate("Master.Title") + " - " + Dictionary.Translate("reportParams.BulkUpdate");

            if (!IsPostBack)
            {
                ddlOrgs.Items.Clear();
                ListItem all = new ListItem("All", "0");
                ddlOrgs.Items.Add(all);
                ddlOrgs.AppendDataBoundItems = true;
                if (SessParam.IsClient)
                {
                    ddlOrgs.DataSource = MLY.Bll.clsOrganization.GetContractorsByClientId((int)Session["OrganizationId"]);
                    ddlOrgs.DataBind();
                }
                else
                {
                    ddlOrgs.DataSource = MLY.Bll.clsOrganization.GetClientsByContractorId((int)Session["OrganizationId"]);
                    ddlOrgs.DataBind();
                }

                               
            }
        }

        protected void SetPopulation(object sender, EventArgs e)
        {
            string Datetype = DateTypeDDL.SelectedValue;
            string StartDate = Utils.SqlDate(DateTime.Parse(txtFromDate.Text));
            string EndDate = Utils.SqlDate(DateTime.Parse(txtToDate.Text));
            string Project = ProjectTextBox.Text.Trim();
            string CustomerId = "", ContractorId = "";
            ResultsPanel.Visible = true;

            if (SessParam.IsClient)
            {
                CustomerId = SessParam.OrganizationId.ToString();
                ContractorId = ddlOrgs.SelectedValue;
            }
            else
            {
                CustomerId = ddlOrgs.SelectedValue;
                ContractorId = SessParam.OrganizationId.ToString();
            }

            RecordsDataSource.SelectParameters.Clear();
            RecordsDataSource.SelectParameters.Add("DateType", Datetype);
            RecordsDataSource.SelectParameters.Add("MinDate", StartDate);
            RecordsDataSource.SelectParameters.Add("MaxDate", EndDate);
            if (Project.Length > 0) RecordsDataSource.SelectParameters.Add("Project", Project);
            RecordsDataSource.SelectParameters.Add("ContractorId", ContractorId);
            RecordsDataSource.SelectParameters.Add("CustomerId", CustomerId);
            RecordsDataSource.SelectParameters.Add("IsClient", SessParam.IsClient ? "1" : "0");

            PopulationGrid.DataSourceID = "RecordsDataSource";
            RecordsDataSource.DataBind();           

            ErrorLabel.Text = "";
        }

        protected void BulkUpdateClick(object sender, EventArgs e)
        {
            bool ActPlannedDeliveryDate = false, ActRequestedDeliveryDate = false, ActPriority = false, ActRemarks = false;
            int tmp;
            ErrorLabel.Text = "";

            if ((PlannedDeliveryDateCB.Checked) && (PlannedDaysText.Text.Trim().Length > 0) && (int.TryParse(PlannedDaysText.Text.Trim(), out tmp)))
                ActPlannedDeliveryDate = true;

            if ((RequestedDeliveryDateCB.Checked) && (RequestedDaysText.Text.Trim().Length > 0) && (int.TryParse(RequestedDaysText.Text.Trim(), out tmp)))
                ActRequestedDeliveryDate = true;

            if ((PriorityCB.Checked) && (PriorityText.Text.Trim().Length > 0) && (int.TryParse(PriorityText.Text.Trim(), out tmp)))
                ActPriority = true;

            if (RemarksCB.Checked)
                ActRemarks = true;

            foreach (GridViewRow r in PopulationGrid.Rows)
            {
                if ((r.FindControl("SelectedCheckBox") as CheckBox).Checked)
                {
                    string WorkOrderId = (r.FindControl("WorkOrderIdHF") as HiddenField).Value;
                    if (ActPlannedDeliveryDate) { SetDate(WorkOrderId, "BulkUpdate_PlannedDeliveryDate", PlannedDaysText.Text.Trim()); }
                    if (ActRequestedDeliveryDate) { SetDate(WorkOrderId, "BulkUpdate_RequestedDeliveryDate", RequestedDaysText.Text.Trim()); }
                    if (ActPriority) { SetPriority(WorkOrderId); }
                    if (ActRemarks) { SetRemarks(WorkOrderId); }
                }
            }
            if (ErrorLabel.Text.Length == 0)
                ErrorLabel.Text = "Operation completed successfully";

            PopulationGrid.DataBind();
        }

        private void SetDate(string WOId, string ProcName, string Value)
        {
            using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MLYConnectionString"].ConnectionString))
            {
                SqlCommand cmd = new SqlCommand(ProcName, conn);
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add("WorkOrderId", SqlDbType.Int);
                cmd.Parameters["WorkOrderId"].Value = WOId;

                cmd.Parameters.Add("Days", SqlDbType.Int);
                cmd.Parameters["Days"].Value = Value;

                try
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text += "Set Date: " + ProcName + " Wo: " + WOId +  " " + ex.Message + "<br /> ";
                }
                finally
                {
                    conn.Close();
                }

            }
        }

        private void SetPriority(string WOId)
        {
            using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MLYConnectionString"].ConnectionString))
            {
                SqlCommand cmd = new SqlCommand("BulkUpdate_Priority", conn);
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add("WorkOrderId", SqlDbType.Int);
                cmd.Parameters["WorkOrderId"].Value = WOId;

                cmd.Parameters.Add("Priority", SqlDbType.Int);
                cmd.Parameters["Priority"].Value = PriorityText.Text.Trim();

                try
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text += "SetPriority. Woid: " + WOId + " " + ex.Message + "<br /> ";
                }
                finally
                {
                    conn.Close();
                }

            }
        }

        private void SetRemarks(string WOId)
        {
            using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MLYConnectionString"].ConnectionString))
            {
                SqlCommand cmd = new SqlCommand("BulkUpdate_Remarks", conn);
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add("WorkOrderId", SqlDbType.Int);
                cmd.Parameters["WorkOrderId"].Value = WOId;

                cmd.Parameters.Add("Remarks", SqlDbType.NVarChar, 4000);
                cmd.Parameters["Remarks"].Value = RemarksTextBox.Text.Trim();

                try
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text += "SetRemarks. Woid: " + WOId + " " + ex.Message + "<br /> ";
                }
                finally
                {
                    conn.Close();
                }

            }
        }
    }
}
